#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h" // 必须以这个顺序 include，由于三个头文件有依赖关系

void sieve(int pipe_left[2])
{
    int num;
    read(pipe_left[0],&num,4);
    if(num == -1)//设置-1为退出数字
        exit(0);
    printf("prime %d\n",num);

    int pipe_right[2];
    pipe(pipe_right);

    if(fork() > 0)
    {
        close(pipe_right[0]);
        int new_num;
        while(read(pipe_left[0],&new_num,4) > 0 && new_num != -1)
        {
            if(new_num % num != 0)//把这些不能整除的数字传给右边管道
            {
                write(pipe_right[1],&new_num,4);
            }
        }
        write(pipe_right[1],&new_num,4);
        wait(0);
        exit(0);
    }
    else
    {
        close(pipe_left[0]);
        close(pipe_right[1]);
        sieve(pipe_right);
    }
}
int main(int argc,char* argv[])
{
    int p1[2];
    pipe(p1);
    if(fork() > 0)
    {
        close(p1[0]);
        int i;
        for(i = 2; i <= 35; ++i)
        {
            write(p1[1],&i,4);
        }
        i = -1;
        write(p1[1],&i,4);
        wait(0);
    }
    else
    {
        close(p1[1]);
        sieve(p1);
    }
    exit(0);
}